package stone926.mods.more_enchantments.mixins;

import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LightningEntity;
import net.minecraft.entity.projectile.ProjectileEntity;
import net.minecraft.entity.projectile.TridentEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.hit.HitResult;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import stone926.mods.more_enchantments.MoreEnchantmentsMod;
import stone926.mods.more_enchantments.interfaces.ILightningEntity;
import stone926.mods.more_enchantments.mixins.accessors.TridentAccessor;
import stone926.mods.more_enchantments.util.EnchantmentUtil;

@Mixin(ProjectileEntity.class)
public abstract class ProjectileEntityMixin extends Entity {

  public ProjectileEntityMixin(EntityType<?> type, World world) {
    super(type, world);
  }

  @Inject(method = "onCollision", at = @At("HEAD"))
  private void onCollision(HitResult hitResult, CallbackInfo ci) {
    if (!hitResult.getType().equals(HitResult.Type.MISS)
      && ((ProjectileEntity) (Object) this) instanceof TridentEntity trident
    ) {
      ItemStack tridentStack = ((TridentAccessor) trident).invokeAsItemStack();
      if (EnchantmentUtil.hasEnchantment(MoreEnchantmentsMod.THUNDER, tridentStack)) {
        LightningEntity lightningEntity = new LightningEntity(EntityType.LIGHTNING_BOLT, world);
        lightningEntity.setPosition(getPos());
        lightningEntity.setChanneler(trident.getOwner() instanceof ServerPlayerEntity p ? p : null);
        ((ILightningEntity) lightningEntity).setOwner(trident.getOwner() != null ? trident.getOwner().getUuid() : null);
        world.spawnEntity(lightningEntity);
      }
    }
  }

}
